package com.intelligentpension.kotlinbluetooth.ble

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputLayout
import com.hjq.toast.ToastUtils
import com.intelligentpension.kotlinbluetooth.R
import com.intelligentpension.kotlinbluetooth.adapter.BEAdapter
import com.intelligentpension.kotlinbluetooth.bt.BtBase
import com.intelligentpension.kotlinbluetooth.bt.BtClient
import com.intelligentpension.kotlinbluetooth.utils.BtReceiver


class BleCustomerActivity : AppCompatActivity(), View.OnClickListener, BtReceiver.Listener,
    BtBase.Listener {

    private val startActivityFor =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            //此处是跳转的result回调方法
            if (it.data != null && it.resultCode == Activity.RESULT_OK) {
                var uri: Uri = it.data!!.data as Uri
                val path = uri.path
                ToastUtils.show("文件的路径是$path")
//                it.data?.getStringExtra(NewWordActivity.EXTRA_REPLY)?.let { reply ->
//                    val word = Word(reply)
//                    wordViewModel.insert(word)
//                }
                if (path != null) {
                    mClient.sendFile(path)
                }else{
                    ToastUtils.show("找不到文件路径")
                }
            } else {
            }
        }


    private lateinit var mRecyler: RecyclerView
    private lateinit var mAdapter: BEAdapter
    private var mDevices: MutableList<BluetoothDevice> = ArrayList<BluetoothDevice>()
    private lateinit var mRediscover: Button
    private lateinit var mBtReceiver: BtReceiver
    private lateinit var mTipText: TextView
    private lateinit var mClient: BtClient
    private lateinit var mTextSend: TextInputLayout
    private lateinit var mSendButton: Button
    private lateinit var mSendFile: Button
    private lateinit var mTvLog: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ble_customer)

        mClient = BtClient(this@BleCustomerActivity)
        mBtReceiver = BtReceiver(this@BleCustomerActivity, this@BleCustomerActivity)

        mRediscover = findViewById<Button>(R.id.rediscover)
        mRediscover.setOnClickListener(this@BleCustomerActivity)
        mRecyler = findViewById<RecyclerView>(R.id.recycler)
        mTipText = findViewById<TextView>(R.id.tip_text)
        mTextSend = findViewById<TextInputLayout>(R.id.text_send)
        mSendButton = findViewById<Button>(R.id.send_button)
        mSendButton.setOnClickListener(this@BleCustomerActivity)
        mSendFile = findViewById<Button>(R.id.send_file)
        mSendFile.setOnClickListener(this@BleCustomerActivity)
        mTvLog = findViewById<TextView>(R.id.tv_log)

        //当前已经配对的设备数量
        val mBt: BluetoothAdapter =
            (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        //只有sdk大于30的时候,才会需要这个权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_SCAN
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
        }
        if (!mBt.isDiscovering) {
            mBt.startDiscovery()
        }
        var bondedDevices: Set<BluetoothDevice> = mBt.bondedDevices
        mDevices.addAll(bondedDevices)

        //设置adapter
        var layoutManager = LinearLayoutManager(this@BleCustomerActivity)
        mRecyler.layoutManager = layoutManager
        mAdapter = BEAdapter(R.layout.item_dev, mDevices)
        mRecyler.adapter = mAdapter


        //条目的点击
        mAdapter.setOnItemClickListener { _, _, position ->
            var dev = mDevices[position]

            if (mClient.isConnected(dev)) {
                ToastUtils.show("已经连接")
                return@setOnItemClickListener
            }
            mClient.connect(dev)

            ToastUtils.show("正在连接....")
            mTipText.text = "正在连接"

        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.rediscover -> {
                mDevices.clear()
                val mBt: BluetoothAdapter =
                    (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter

                //先添加已经配对的设备
                var bondedDevices: Set<BluetoothDevice> = mBt.bondedDevices
                mDevices.addAll(bondedDevices)

                //只有sdk大于30的时候,才会需要这个权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        return
                    }
                }

                if (!mBt.isDiscovering) {
                    mBt.startDiscovery()
                }

            }
            R.id.send_button -> {

                if (mClient.isConnected(null)) {
                    var msg = mTextSend.editText!!.text.toString().trim()
                    if (TextUtils.isEmpty(msg)) {
                        ToastUtils.show("发送的消息不能为空")
                        return
                    } else {
                        mClient.sendMsg(msg);
                        ToastUtils.show("发送的消息是$msg")
                    }
                } else {
                    ToastUtils.show("请先连接蓝牙")
                }
            }
            R.id.send_file -> {
                ToastUtils.show("点击了")
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                intent.type = "*/*"
                startActivityFor.launch(intent)

            }
        }

    }

    //接受广播发送过来的蓝牙
    @SuppressLint("MissingPermission")
    override fun foundDev(dev: BluetoothDevice?) {
        if (mDevices.contains(dev))
            return
        mDevices.add(dev!!);
        mAdapter.notifyDataSetChanged()
//        try {
//            mDevices.forEach { s ->
//                if (mClient.isConnected(s)) {
//                    var name = String.format("已经连接%s", s.name)
//                    mTipText.text = name
//                }
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
    }

    override fun onDestroy() {
        unregisterReceiver(mBtReceiver)
        mClient.unListener()
        mClient.closeSocket()
        super.onDestroy()
    }

    //收到的信息
    @SuppressLint("MissingPermission")
    override fun socketNotify(state: Int, obj: Any?) {
        if (isDestroyed) return
        var msg: String = ""
        when (state) {
            BtBase.Listener.CONNECTED -> {
                var dev = obj as BluetoothDevice
                msg = String.format("与%s(%s)连接成功", dev.name, dev.address)
                mTipText.text = msg
            }
            BtBase.Listener.DISCONNECTED -> {
                msg = "连接断开"
                mTipText.text = msg
            }
            BtBase.Listener.MSG -> {
                msg = String.format("\n%s", obj)
                mTvLog.append(msg)
            }
        }
        ToastUtils.show(msg)
    }
}